package me.evis.mobile.sms2cal;

import java.util.List;

import me.evis.mobile.sms2cal.model.CalEvent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;

public class CalendarUtil {

    private CalendarUtil() {
        // no instance
    }

    public static int addToCalendar(Context context, CalEvent event) {
        ContentValues values = new ContentValues();
        
        values.put("calendar_id", 1);
        values.put("title", event.summary);
        values.put("description", event.description);
        values.put("eventLocation", event.location);
        values.put("dtstart", event.dtStart.getTime());
        values.put("dtend", event.dtEnd.getTime());
        values.put("hasAlarm", (event.getCalAlarms().size() > 0) ? 1 : 0);
//        values.put("eventTimezone", "Asia/Hong_Kong");
        
        Uri eventsUri = Uri.parse(getCalendarUriBase(context) + "events");
        Uri insertedUri = context.getContentResolver().insert(eventsUri, values);
        return Integer.parseInt(insertedUri.getLastPathSegment());
//        Intent intent = new Intent(Intent.ACTION_EDIT);  
//      intent.setType("vnd.android.cursor.item/event");
//      intent.putExtra("title", "Some title");
//      intent.putExtra("description", "Some description");
//      intent.putExtra("beginTime", eventStartInMillis);
//      intent.putExtra("endTime", eventEndInMillis);
//      startActivity(intent);
//      Intent intent = new Intent(Intent.ACTION_VIEW);
//        //Android 2.2+
//        intent.setData(Uri.parse("content://com.android.calendar/events/1"));  
//        //Android 2.1 and below.
//        //intent.setData(Uri.parse("content://calendar/events/" + String.valueOf(calendarEventID)));    
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//            | Intent.FLAG_ACTIVITY_SINGLE_TOP
//            | Intent.FLAG_ACTIVITY_CLEAR_TOP
//            | Intent.FLAG_ACTIVITY_NO_HISTORY
//            | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
//        startActivity(intent);
    }
    
    public static void removeFromCalendar(Context context, int id) {
        context.getContentResolver().delete(getEventWithIdUri(context, id), null, null);
    }
    
    public static void viewInCalendar(Context context, int id) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(getEventWithIdUri(context, id));
        context.startActivity(intent);
    }
    
    private static Uri getEventWithIdUri(Context context, int id) {
        return ContentUris.withAppendedId(Uri.parse(getCalendarUriBase(context) + "events"), id);
    }
    
    /*
     * http://code.google.com/p/android-calendar-provider-tests/source/browse/trunk/src/com/androidbook/androidcalendar/CalendarActivity.java
     * 
     * Determines if it's a pre 2.1 or a 2.2 calendar Uri, and returns the Uri
     */
    private static String getCalendarUriBase(Context context) {
        ContentResolver resolver = context.getContentResolver();
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor c = null;
        try {
            c = resolver.query(calendars, null, null, null, null);
        } catch (Exception e) {
            // Ignore.
        }

        if (c != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                c = resolver.query(calendars, null, null, null, null);
            } catch (Exception e) {
                // Ignore.
            }

            if (c != null) {
                calendarUriBase = "content://com.android.calendar/";
            }

        }
        
        if (c != null) {
            c.close();
            c = null;
        }

        return calendarUriBase;
    }
    
    @Deprecated
    protected static boolean isNewCalendar(Context context) {
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("content://com.android.calendar/events/"));
        List<ResolveInfo> list = pm.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0) {
            return true;
        } else {
            intent.setData(Uri.parse("content://calendar/events/"));
            list = pm.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            if (list.size() > 0) {
                return false;
            }
        }
        
        throw new IllegalStateException("No Calendar app installed in the device.");
    }
}
